<?php

namespace App\Controller\Api\Consultant;

use App\Constants\ErrorCode;
use App\Controller\Api\BaseController;
use App\Helper\CommonHelper;
use App\Helper\HashHelper;
use App\Model\AccountTransaction;
use App\Model\AvatarExample;
use App\Model\Balance;
use App\Model\ConsultantAlbum;
use App\Model\ConsultantApply;
use App\Model\ConsultantAuthenticationType;
use App\Model\ConsultantDatum;
use App\Model\ConsultantVideo;
use App\Model\LoginLog;
use App\Model\User;
use App\Model\UserBlacklist;
use App\Model\UserDatum;
use App\Model\UserFeedbackLog;
use App\Model\UserNotice;
use App\Model\UserReportLog;
use App\Model\Withdrawal;
use App\Service\UserService;
use App\Support\AwsS3;
use Exception as ExceptionAlias;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use function _PHPStan_b8e553790\React\Promise\Stream\first;
use function Swoole\Coroutine\Http\get;
use App\Middleware\JWTAuthConsultantMiddleware;

/**
 * @Middleware(JWTAuthConsultantMiddleware::class)
 * @Controller(prefix="/consultant/v1/user")
 */
class UserController extends BaseController
{


    /**
     * @Inject()
     * @var UserService
     */
    protected $userService;


    /**
     *
     * @RequestMapping(path="tokenRefresh")
     * @return ResponseInterface
     * @throws InvalidArgumentException
     */
    public function tokenRefresh()
    {

        $lastLogin = LoginLog::where(['uid' => $this->uid()])->orderBy('id', 'desc')->first();
        if (is_null($lastLogin)) {
            return $this->response->returnFail();
        }

        return $this->userService->consultantUserLogin($this->uid(), $lastLogin['platform'], $lastLogin['login_account']);

    }


    /**
     * 申请认证
     * @RequestMapping(path="applyAuthentication")
     * @return ResponseInterface
     */
    public function applyAuthentication()
    {


        // todo 首先查询是否存在正在申请的资料认证

        $apply = ConsultantApply::where(['status' => 0, 'uid' => $this->uid()])->first();

        //有正在审核的资料认证
        if ($apply) {
            return $this->response->returnFail(ErrorCode::APPLY_REVIEW);
        }

        $params = $this->request->post();

        $this->validate($params, [
            'userType' => 'required',
            'accountFront' => 'required',
            'accountBack' => 'required',
            'accountHand' => 'required',
            'name' => 'required',
            'education' => 'required',
            'educationImg' => 'required',
            'certificate' => 'required',
            'certificateImg' => 'required',
            'direction' => 'required',
            'crowd' => 'required',
            'style' => 'required',
            'genre' => 'required',
            'introduce' => 'required',
            'startWork' => 'required',
            'country' => 'required',
            'language' => 'required',
            'price' => 'required',
            'classId' => 'required',
            'contactId' => 'required',
            'contact' => 'required',
        ]);


        $consultantInfo = ConsultantDatum::where(['uid' => $this->uid()])->first();

        $year = ceil((time() - $params['startWork']) / 86400);


        $data = [
            'uid' => $this->uid(),
            'user_type' => $params['userType'],
            'account_front' => $params['accountFront'],
            'account_back' => $params['accountBack'],
            'account_hand' => $params['accountHand'],
            'name' => $params['name'],
            'education' => $params['education'],//最高学历
            'education_img' => $params['educationImg'],//最高学历图片
            'certificate' => $params['certificate'],//证书名称
            'certificate_img' => $params['certificateImg'],//证书图片 多个逗号
            'direction' => $params['direction'],//擅长方向
            'crowd' => $params['crowd'],//擅长人群
            'style' => $params['style'],//擅长风格
            'genre' => $params['genre'],//擅长流派
            'introduce' => $params['introduce'],//个人简介
            'start_work' => $params['startWork'],//工作开始时间
            'years' => $year,//工作年限
            'country' => $params['country'],//国家
            'language' => $params['language'],//语言
            'price' => $params['price'],//语言 申请的定价
            'class_id' => $params['classId'],//课时Id
            'contact_id' => $params['contactId'],//联系方式类型id
            'contact' => $params['contact'],//contact 联系方式
        ];

        //判断是否之前已经成功申请过 区别是申请认证 还是 资料修改
        if (is_null($consultantInfo)) {
            $data['type'] = 1;
        } else {
            $data['type'] = 2;
            $data['old_log'] = json_encode($consultantInfo);
        }


        //todo  单独处理头像等基本信息

        $baseInfo = [
            'nickname' => $params['name'],
            'head' => $params['head'],
            'gender' => $params['gender'],
            'birthday' => $params['birthday'],
            'country' => $params['country'],
            'language' => intval($params['language']),
            'update_time' => time(),
            'status' => 1
        ];


        //开始写入申请数据

        Db::beginTransaction();
        try {

            $rel = ConsultantApply::insert($data);


            $userDatum = UserDatum::where(['uid' => $this->uid()])->first();

            if (is_null($userDatum)) {
                UserDatum::insert($baseInfo);
            }

            UserDatum::where(['uid' => $this->uid()])->update($baseInfo);

            Db::commit();

            $backInfo = ['email' => 'xxx@yyy.com', 'wechat' => 'xinlizixun', 'code' => 'https://img.seekingaround.com/seekingaround/dev/2023-06-07/647fec87cb4c9fNqgntQBYYIM9CAP.png'];
            return $this->response->returnSuccess($backInfo);

        } catch (ExceptionAlias $e) {
            Db::rollBack();

            recordExceptionLog('提交申请认证资料失败', $e->getMessage());
            return $this->response->returnFail();
        }


    }


    /**
     * 修改认证资料
     * @RequestMapping(path="editApplyDatum")
     * @return ResponseInterface
     */
    public function editApplyDatum()
    {


        $apply = ConsultantApply::where(['status' => 0, 'uid' => $this->uid()])->first();

        //有正在审核的资料认证
        if ($apply) {
            return $this->response->returnFail(ErrorCode::APPLY_REVIEW);
        }

        $params = $this->request->post();

        $this->validate($params, [
            'country' => 'required',
            'language' => 'required',
            'education' => 'required',
            'educationImg' => 'required',
            'certificate' => 'required',
            'certificateImg' => 'required',
            'direction' => 'required',
            'crowd' => 'required',
            'style' => 'required',
            'genre' => 'required',
            'introduce' => 'required',
            'startWork' => 'required',
            'price' => 'required',
            'classId' => 'required',
            'contactId' => 'required',
            'contact' => 'required',
        ]);


        $timeDiff = (time() - $params['startWork']) / 86400;
        $year = ceil($timeDiff);


        $oldDatum = ConsultantApply::where(['uid' => $this->uid(), 'status' => 1])->orderByDesc('id')->first();

        if (is_null($oldDatum)) {
            return $this->response->returnFail();
        }
        $oldDatum = $oldDatum->toArray();


        $data = [
            'uid' => $this->uid(),
            'user_type' => $oldDatum['user_type'],
            'account_front' => $oldDatum['account_front'],
            'account_back' => $oldDatum['account_back'],
            'account_hand' => $oldDatum['account_back'],
            'name' => $oldDatum['name'],
            'education' => $params['education'],//最高学历
            'education_img' => $params['educationImg'],//最高学历图片
            'certificate' => $params['certificate'],//证书名称
            'certificate_img' => $params['certificateImg'],//证书图片 多个逗号
            'direction' => $params['direction'],//擅长方向
            'crowd' => $params['crowd'],//擅长人群
            'style' => $params['style'],//擅长风格
            'genre' => $params['genre'],//擅长流派
            'introduce' => $params['introduce'],//个人简介
            'start_work' => $params['startWork'],//工作开始时间
            'years' => $year,//工作年限
            'country' => $params['country'],//国家
            'language' => $params['language'],//语言
            'price' => $params['price'],//语言 申请的定价
            'class_id' => $params['classId'],//课时Id
            'contact_id' => $params['contactId'],//联系方式类型id
            'contact' => $params['contact'],//contact 联系方式
        ];

        //开始写入申请数据

        Db::beginTransaction();
        try {

            $rel = ConsultantApply::insert($data);

            Db::commit();

            $backInfo = ['email' => 'xxx@yyy.com', 'wechat' => 'xinlizixun', 'code' => 'https://img.seekingaround.com/seekingaround/dev/2023-06-07/647fec87cb4c9fNqgntQBYYIM9CAP.png'];
            return $this->response->returnSuccess($backInfo);

        } catch (ExceptionAlias $e) {
            Db::rollBack();

            recordExceptionLog('提交修改认证申请认证资料失败', $e->getMessage());
            return $this->response->returnFail();
        }

    }


    /**
     * 修改咨询师基本资料
     * @RequestMapping(path="editBaseInfo")
     * @return ResponseInterface
     */
    public function editBaseInfo()
    {

        $params = $this->request->post();

        $this->validate($params, [
            'head' => 'required',
            'name' => 'required',
            'gender' => 'required',
            'birthday' => 'required'
        ]);

        $baseInfo = [
            'nickname' => $params['name'],
            'head' => $params['head'],
            'gender' => $params['gender'],
            'birthday' => $params['birthday'],
            'update_time' => time(),
            'status' => 1
        ];

        // 后期考虑这里也加审核

        $rel = UserDatum::where(['uid' => $this->uid()])->update($baseInfo);

        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }


    }


    /**
     * 咨询师认证资料详情
     * @RequestMapping(path="consultantDatumInfo")
     * @return ResponseInterface
     */
    public function consultantDatumInfo()
    {


        $info = Db::table('consultant_datum')->where(['uid' => $this->uid()])->first();

        $info = (array)$info;
        if (empty($info)){
            $info = null;
        }

        return $this->response->returnSuccess(['info' => $info]);


    }


    /**
     * 咨询师基本信息接口
     * @RequestMapping(path="consultantBaseUserInfo")
     * @return ResponseInterface
     */
    public function consultantBaseUserInfo()
    {


        $info = User::from('user as a')
            ->leftJoin('user_datum as b', 'a.id', '=', 'b.uid')
            ->select(['b.uid','a.num', 'b.head', 'b.nickname', 'a.role', 'a.apple_id', 'wechat_id', 'email', 'phone', 'gender', 'birthday', 'google_id', 'facebook_id', 'a.password'])
            ->where(['a.id' => $this->uid()])
            ->first();

        if (!$info) {
            return $this->response->returnFail();
        }
        $info = $info->toArray();


        $apply = ConsultantApply::where(['uid' => $this->uid(), 'status' => 0])->exists();


        if ($apply) {
            $info['authStatus'] = 0;//认证审核中
        } else {
            if ($info['role'] > 0) {
                $info['authStatus'] = 1;//认证成功
            } else {
                $info['authStatus'] = 2;//未进行认证
            }
        }

        if (!empty($info['password'])) {
            $info['password'] = 1;
        } else {
            $info['password'] = 0;
        }


        $info['roleName'] = ConsultantAuthenticationType::where(['user_type' => $info['role'], 'lang' => getLang()])->value('name');


        $info['album'] = (int)ConsultantAlbum::where(['uid' => $this->uid()])->exists();
        $info['video'] = (int)ConsultantVideo::where(['uid' => $this->uid()])->exists();


        return $this->response->returnSuccess(['info' => $info]);

    }


    /**
     * 头像示范接口
     * @RequestMapping(path="avatarExampleList")
     * @return ResponseInterface
     */
    public function avatarExampleList()
    {


        $list = AvatarExample::where(['lang' => getLang()])->get()->toArray();

        return $this->response->returnSuccess(['list' => $list]);


    }


    /**
     * 上传图片
     * @RequestMapping(path="getAwsPresagedUrl")
     */
    public function getAwsPresagedUrl()
    {
        $aws = new AwsS3();

        $file = $this->request->post('file');
        $ext = explode('/', $file)[1] ?? 'jpg';

        $pathDev = config('app_env') == 'dev' ? 'dev/' : '';
        $path = 'consultant/' . $pathDev . date('Y-m-d') . '/' . CommonHelper::imgName() . '.' . $ext;
        $cdnurl = env('IMG_URL') . '/' . $path;
        $url = $aws->getPresagedUrl($path);

        return $this->response->returnSuccess(['url' => $url, 'cdnUrl' => $cdnurl]);


    }


    /**
     * @RequestMapping(path="consultantApplyTypeList")
     * @return ResponseInterface
     */
    public function consultantApplyTypeList()
    {

        $lang = getLang();


        $list = ConsultantAuthenticationType::orderByDesc('sort')->get()->toArray();

        return $this->response->returnSuccess(['list' => $list]);


    }


    /**
     * 用户反馈
     * @RequestMapping(path="feedback")
     */
    public function feedback()
    {

        $params = $this->request->post();

        $this->validate($params, [
            'description' => 'required',
            'type' => 'required'
        ]);


        $insertData = [
            'type' => $params['type'] ?? '',
            'description' => $params['description'] ?? '',
            'url' => $params['url'] ?? '',
            'uid' => $this->uid(),
            'create_time' => time()
        ];
        $rel = UserFeedbackLog::insert($insertData);
        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }

    }


    /**
     * 我的相册列表
     * @RequestMapping(path="myAlbum")
     * @return ResponseInterface
     *
     */
    public function myAlbum()
    {


        $list = ConsultantAlbum::where(['uid' => $this->uid()])->select(['id', 'uid', 'status', 'photo'])->orderBy('id')->get()->toArray();


        return $this->response->returnSuccess(['list' => $list]);

    }

    /**
     * @RequestMapping(path="addAlbum")
     * @return ResponseInterface
     */
    public function addAlbum()
    {
        $params = $this->request->post();

        $this->validate($params, [
            'photo' => 'required'
        ]);


        $num = count($params['photo']);


        $count = ConsultantAlbum::where(['uid' => $this->uid()])->count();


        if ($num + $count > 9) {
            return $this->response->returnFail(ErrorCode::PHOTO_MAX9);
        }

        $data = [];
        foreach ($params['photo'] as $k => $v) {
            $data[] = [
                'uid' => $this->uid(),
                'photo' => $v,
                'status' => 0,
                'create_time' => time(),
            ];

        }


        $rel = ConsultantAlbum::insert($data);


        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }


    }


    /**
     * @RequestMapping(path="delAlbum")
     * @return ResponseInterface
     *
     * @throws ExceptionAlias
     */
    public function delAlbum()
    {
        $params = $this->request->post();

        $this->validate($params, [
            'id' => 'required'
        ]);

        $info = ConsultantAlbum::where(['id' => $params['id'], 'uid' => $this->uid()])->first();

        if (is_null($info)) {
            return $this->response->returnSuccess();
        }

        $info->delete();

        return $this->response->returnSuccess();

    }


    /**
     * @RequestMapping(path="myVideo")
     * @return ResponseInterface
     */
    public function myVideo()
    {

        $info = ConsultantVideo::where(['uid' => $this->uid()])->orderByDesc('id')->first();

        if (!is_null($info)) {
            $info = $info->toArray();
        }

        return $this->response->returnSuccess(['info' => $info]);

    }


    /**
     * @RequestMapping(path="addVideo")
     * @return ResponseInterface
     */
    public function addVideo()
    {

        $params = $this->request->post();

        $info = ConsultantVideo::where(['uid' => $this->uid()])->first();


        $this->validate($params, [
            'video' => 'required',
            'cover' => 'required',
        ]);

        $data = [
            'uid' => $this->uid(),
            'video' => $params['video'],
            'cover' => $params['cover'],
            'status' => 0,
            'create_time' => time()
        ];


        if ($info) {
            $rel = ConsultantVideo::where(['id' => $info['id']])->update($data);
        } else {
            $rel = ConsultantVideo::insert($data);
        }


        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }


    }


    /**
     * 系统参数信息
     * @RequestMapping(path="sysSettingInfo")
     * @return ResponseInterface
     */
    public function sysSettingInfo()
    {
        $data = [
            'helpCenterUrl' => 'https://h5.soulcare.plus/helpCenter',// 帮助中心地址
            'videoDemo' => 'http://vd3.bdstatic.com/mda-pg9kiwpj1ijpx28h/360p/h264/1688999459967986656/mda-pg9kiwpj1ijpx28h.mp4',//视频地址
        ];

        return $this->response->returnSuccess($data);
    }


    /**
     *绑定第三方账号
     * @RequestMapping(path="bindTripartite")
     * @return ResponseInterface
     */
    public function bindTripartite()
    {

        //todo 后面加 只能绑定一次的逻辑


        $params = $this->request->post();

        $this->validate($params, [
            'type' => 'required',
            'account' => 'required'
        ]);


        $account = User::where(['id' => $this->uid()])->value($params['type'] . '_id');
        if (!empty($account)) {
            return $this->response->returnFail(ErrorCode::BIND_ALREADY);
        }

        $data = [
            $params['type'] . '_id' => $params['account'],
            'update_time' => time()
        ];

        $rel = User::where(['id' => $this->uid()])->update($data);

        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }


    }


    /**
     * @RequestMapping(path="bindPhone")
     * @return ResponseInterface
     */
    public function bindPhone()
    {
        //todo 后面加 只能绑定一次的逻辑
        $params = $this->request->post();

        $this->validate($params, [
            'phone' => 'required',
            'code' => 'required'
        ]);

        $rel = $this->checkBindCode($params['phone'], $params['code']);
        if (!$rel) {
            return $this->response->returnFail(ErrorCode::REGISTER_CODE_FAIL);
        }

        $phone = User::where(['id' => $this->uid()])->value('phone');

        if (!empty($phone)) {
            return $this->response->returnFail(ErrorCode::BIND_ALREADY);
        }

        $data = [
            'phone' => $params['phone'],
            'update_time' => time()
        ];


        $rel = User::where(['id' => $this->uid()])->update($data);


        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }


    }


    /**
     *绑定邮箱
     * @RequestMapping(path="bindEmail")
     * @return ResponseInterface
     */
    public function bindEmail()
    {
        //todo 后面加 只能绑定一次的逻辑
        $params = $this->request->post();

        $this->validate($params, [
            'email' => 'required',
            'code' => 'required'
        ]);

        $rel = $this->checkBindCode($params['phone'], $params['code']);
        if (!$rel) {
            return $this->response->returnFail(ErrorCode::REGISTER_CODE_FAIL);
        }

        $phone = User::where(['id' => $this->uid()])->value('email');

        if (!empty($phone)) {
            return $this->response->returnFail(ErrorCode::BIND_ALREADY);
        }

        $data = [
            'email' => $params['email'],
            'update_time' => time()
        ];


        $rel = User::where(['id' => $this->uid()])->update($data);


        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }


    }


    /**
     * 验证验证码是否有效
     * @param $account
     * @param $code
     * @return true
     */
    public function checkBindCode($account, $code)
    {


        return true;

    }


    /**
     * @RequestMapping(path="changePassword")
     * @return ResponseInterface
     */
    public function changePassword()
    {

        $params = $this->request->post();

        $this->validate($params, [
            'oldPassword' => 'required',
            'newPassword' => 'required',
        ]);


        $userInfo = User::where(['id' => $this->uid()])->select(['id', 'password'])->first();

        if (!password_verify($params['oldPassword'], $userInfo->password)) {
            return $this->response->returnFail(ErrorCode::LOGIN_PASSWORD);
        }


        $newPassword = HashHelper::make($params['newPassword']);


        $rel = User::where(['id' => $this->uid()])->update(['password' => $newPassword, 'update_time' => time()]);


        if ($rel) {
            //退出登录
            $guard = $this->guard();
            $guard->logout();

            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }


    }

    /**
     * @RequestMapping(path="setPassword")
     * @return ResponseInterface
     */
    public function setPassword()
    {
        $params = $this->request->post();

        $this->validate($params, [
            'password' => 'required'
        ]);

        $rel = $this->checkBindCode($params['account'], $params['code']);

        if (!$rel) {
            return $this->response->returnFail(ErrorCode::REGISTER_CODE_FAIL);
        }


        $password = User::where(['id' => $this->uid()])->value('password');

        if (!empty($password)) {
            return $this->response->returnFail(ErrorCode::PASSWORD_ISSET);
        }

        $newPassword = HashHelper::make($params['password']);

        $rel = User::where(['id' => $this->uid()])->update(['password' => $newPassword, 'update_time' => time()]);

        if ($rel) {
            //退出登录
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }


    }

    /**
     * @RequestMapping(path="logOut")
     * @return ResponseInterface
     */
    public function logOut()
    {
        $guard = $this->guard();
        $guard->logout();

        return $this->response->returnSuccess();
    }


    /**
     * 咨询师首页数据信息
     * @RequestMapping(path="indexInfo")
     * @return ResponseInterface
     */
    public function indexInfo()
    {

        $amount = Balance::where(['uid' => $this->uid()])->select(['amount', 'currency', 'prefix'])->first();
        if (is_null($amount)) {
            $data['amount'] = '0';
            $currency = UserDatum::where(['uid' => $this->uid()])->value('currency');
            $data['currency'] = $currency ?? 'USD';
            $data['prefix'] = '$';
        } else {
            $data['amount'] = $amount['amount'];
            $data['currency'] = $amount['currency'];
            $data['prefix'] = $amount['prefix'];
        }


        $data['pending'] = 1;

        return $this->response->returnSuccess(['info' => $data]);

    }


    /**
     * 账变历史
     * @RequestMapping(path="accountTransactionLog")
     * @return ResponseInterface
     */
    public function accountTransactionLog()
    {


        $where[] = ['a.uid', '=', $this->uid()];

        $type = $this->request->query('type');

        if (!empty($type)) {
            $where[] = ['a.type', '=', $type];
        }
        $lang = getLang();

        $model = AccountTransaction::from('account_transaction as a')
            ->leftJoin('balance_type as d', 'a.type', '=', 'd.id')
            ->leftJoin('balance_type_trans as b', function ($query) use ($lang) {
                $query->on('b.balance_type_id', '=', 'a.type');
                $query->where('b.lang', '=', $lang);
            })
            ->leftJoin('balance_type_suffix_trans as c', function ($query) use ($lang) {
                $query->on('c.balance_type_suffix_id', '=', 'a.type_suffix');
                $query->where('c.lang', '=', $lang);
            })
            ->where($where)
            ->select(['a.*', 'd.url', 'b.name as typeName', 'c.name as typeSuffixName'])
            ->orderByDesc('a.id');


        $list = page($model);

        return $this->response->returnSuccess(['list' => $list]);


    }

    /**
     * 申请提现
     * @RequestMapping(path="applyWithdrawal")
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function applyWithdrawal()
    {



        $params = $this->request->post();

        $this->validate($params, [
            'wid' => 'required',
            'amount' => 'required',
            'accountName' => 'required',
            'account' => 'required',
        ]);

        $userAmount = Balance::where(['uid' => $this->uid()])->first();

        if ($userAmount['amount'] < $params['amount']) {
            return $this->response->returnFail(ErrorCode::WITHDRAWAL_AMOUNT_FAIL);
        }



        // 开始进行提现申请

        Db::beginTransaction();
        try {

            $rel = Balance::balanceLog($this->uid(), $params['amount'], 0, 1, 1, [], '用户申请提现');

            if (!$rel) {
                Db::rollBack();
                return $this->response->returnFail();
            }


            $withdrawalData = [
                'uid' => $this->uid(),
                'wid' => $params['wid'],
                'amount' => $params['amount'],
                'currency' => $userAmount['currency'],
                'account_name' => $params['accountName'],
                'account' => $params['account'],
                'create_time' => time(),
                'status' => 0
            ];

            Withdrawal::insert($withdrawalData);
            Db::commit();
            return $this->response->returnSuccess();
        } catch (\Exception $e) {
            Db::rollBack();



            recordExceptionLog('申请提现失败', $e->getMessage());
            return $this->response->returnFail();
        }


    }


    /**
     * 工作数据
     * @RequestMapping(path="workData")
     * @return ResponseInterface
     */
    public function workData()
    {

        $data = [
            [
                'name' => 'Completed order',
                'num' => '6465',
                'icon' => 'https://img.seekingaround.com/seekingaround/dev/2023-06-08/6481399c355b4sIEq0AINkQYm8adk.jpeg'
            ],
            [
                'name' => 'Service times',
                'num' => '689h 48min',
                'icon' => 'https://img.seekingaround.com/seekingaround/dev/2023-06-08/6481399c355b4sIEq0AINkQYm8adk.jpeg'
            ],
            [
                'name' => 'Service users',
                'num' => '658',
                'icon' => 'https://img.seekingaround.com/seekingaround/dev/2023-06-08/6481399c355b4sIEq0AINkQYm8adk.jpeg'
            ],
            [
                'name' => 'Average duration',
                'num' => '65min',
                'icon' => 'https://img.seekingaround.com/seekingaround/dev/2023-06-08/6481399c355b4sIEq0AINkQYm8adk.jpeg'
            ],
            [
                'name' => 'Completed order',
                'num' => '96.5%',
                'icon' => 'https://img.seekingaround.com/seekingaround/dev/2023-06-08/6481399c355b4sIEq0AINkQYm8adk.jpeg'
            ],

        ];


        return $this->response->returnSuccess(['info' => $data]);
    }


    /**
     * @RequestMapping(path="userNoticeInfo")
     * @return ResponseInterface
     */
    public function userNoticeInfo()
    {
        $info = UserNotice::where(['uid' => $this->uid()])->first();

        //还没设置进行初始化设置
        if (is_null($info)) {
            $insertData = [
                'uid' => $this->uid(),
                'email' => 1,
                'phone' => 1,
                'update_time' => time(),
            ];
            UserNotice::insert($insertData);

            return $this->response->returnSuccess(['info' => ['email' => 1, 'phone' => 1]]);
        } else {
            return $this->response->returnSuccess(['info' => ['email' => $info['email'], 'phone' => $info['phone']]]);
        }

    }

    /**
     * 修改用户通知权限
     * @RequestMapping(path="setUserNotice")
     * @return ResponseInterface
     */
    public function setUserNotice()
    {

        $params = $this->request->post();

        $data = [];
        if (isset($params['email'])) {
            $data['email'] = $params['email'];
        }
        if (isset($params['phone'])) {
            $data['phone'] = $params['phone'];
        }

        if (!empty($data)) {
            $data['update_time'] = time();
            UserNotice::where(['uid' => $this->uid()])->update($data);
        }

        return $this->response->returnSuccess();

    }


    /**
     * @RequestMapping(path="reportUser")
     */
    public function reportUser()
    {

        $params = $this->request->post();

        $this->validate($params, [
            'uid' => 'required',
            'rid' => 'required'
        ]);


        $insertData = [
            'uid' => $this->uid(),
            'rid' => $params['rid'],
            'type' => 2,
            'status' => 0,
            'report_uid' => $params['uid'],
            'create_time' => time()
        ];

        $rel = UserReportLog::insert($insertData);

        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();
        }

    }


    /**
     * 我的黑名单
     * @RequestMapping(path="myBlackList")
     * @return ResponseInterface
     */
    public function myBlackList()
    {

        $list = UserBlacklist::getMyBlackList($this->uid());

        return $this->response->returnSuccess(['list' => $list]);

    }


    /**
     * 加入黑名单
     * @RequestMapping(path="addBlackList")
     * @return ResponseInterface
     */
    public function addBlackList()
    {


        $params = $this->request->post();
        $blackId = $this->request->post('uid');

        $this->validate($params, [
            'uid' => 'required'
        ]);

        $exists = UserBlacklist::where(['uid' => $this->uid(), 'blacked_uid' => $blackId])->exists();
        if ($exists) {
            return $this->response->returnSuccess();
        }

        $insertData = [
            'uid' => $this->uid(),
            'blacked_uid' => $blackId,
            'create_time' => time()
        ];
        $rel = UserBlacklist::insert($insertData);

        if ($rel) {
            return $this->response->returnSuccess();
        } else {
            return $this->response->returnFail();

        }

    }


    /**
     *移除黑名单
     * @RequestMapping(path="removeBlack")
     * @return ResponseInterface
     * @throws \Exception
     */
    public function removeBlack()
    {
        $params = $this->request->post();
        $blackId = $this->request->post('uid');
        $this->validate($params, [
            'uid' => 'required'
        ]);

        $info = UserBlacklist::where(['uid' => $this->uid(), 'blacked_uid' => $blackId])->first();
        if (!is_null($info)) {
            $info->delete();
        }
        return $this->response->returnSuccess();
    }




}